package com.gy.paidao.util.map;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.AMapUtils;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptor;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.LatLngBounds;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.gy.paidao.R;
import com.gy.paidao.util.LejuLocationClient;

import java.util.List;

/**
 * @author GY
 * @date 2015/5/22
 * @Description: 高德地图工具类
 */

public abstract class AMapUitls implements AMap.OnMarkerClickListener, AMap.OnCameraChangeListener,
        AMap.OnInfoWindowClickListener, AMap.InfoWindowAdapter, LejuLocationClient.OnLocationListener,
        AMap.OnMapTouchListener, AMap.OnMapClickListener {

    private AMap aMap;
    private MapView mMapView;//地图
    private Context mContext;
    private Drawable marker;
    public static int ZOOM_DEFAULT = 10;//显示区域时zoom等级
    public static int ZOOM_DETAIL = 19;//显示详情时zoom等级
    public static int padding = 200;
    private List<? extends MapBaseBean> list;//数据源
    private MapBaseDrawable mMapBaseDrawable;//marker和PopupOverlay的bitmap的基类
    private LatLng center, myLoc;
    private LejuLocationClient locationClient;//定位
    private Marker centerMarker;
    /**
     * 默认的比例尺
     */
    public static final int defaultZoomSize = 16;
    private float zoom;//当前zoom
    /**
     * 移动再次请求距离
     */
    private final int MAX_DISTANCE = 1000;
    private boolean moveSelf = false;//是否一屏显示所有marker
    private boolean touchFlag = false;//是否通过触摸滑动地图

    public AMapUitls(Context context, final MapView mMapView, Drawable marker) {
        this.mContext = context;
        this.mMapView = mMapView;
        this.marker = marker;
        aMap = mMapView.getMap();
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.getUiSettings().setZoomControlsEnabled(false);//设置地图缩放按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.setOnMarkerClickListener(this);// 设置点击marker事件监听器
        aMap.setOnCameraChangeListener(this);
        aMap.setOnInfoWindowClickListener(this);// 设置点击infoWindow事件监听器
        aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式
        aMap.setOnMapTouchListener(this);
        aMap.setOnMapClickListener(this);
        locationClient = LejuLocationClient.getInstance(context);
    }

    /**
     * 设置比例尺
     */
    public void setZoom(int zoomSize) {
        if (null != aMap) {
            aMap = mMapView.getMap();
        }
        if (null != aMap) {
            zoom = zoomSize <= 0 ? defaultZoomSize : zoomSize;
            aMap.moveCamera(CameraUpdateFactory.zoomTo(zoom));//设置地图zoom级别
        }
    }

    /**
     * 获取比例尺
     */
    public float getScalePerPixel() {
        if (null != aMap) {
            return aMap.getScalePerPixel();
        }
        return 0;
    }

    /**
     * 增加我的位置
     *
     * @param latidude  维度
     * @param longitude 经度
     */
    public void setCenter(double latidude, double longitude) {
        center = new LatLng(latidude, longitude);
    }

    /** 获取地图中心店*/
    public LatLng getCenter() {
        return center;
    }

    /**
     * 设置地图中心点并移动
     */
    public void setAndMoveCenter(double latidude, double longitude) {
        center = new LatLng(latidude, longitude);
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(center));
    }

    /**
     * 设置定位到的位置
     */
    public void setMyLoc(double latidude, double longitude) {
        myLoc = new LatLng(latidude, longitude);
        if (centerMarker != null) {
            centerMarker.remove();
        }
        aMap.addMarker(new MarkerOptions()
                .position(myLoc)
                .icon(BitmapDescriptorFactory
                        .fromResource(R.mipmap.ic_map_logo))
                .draggable(true));
    }

    /**
     * 地图是否显示左右marker
     */
    public void setMoveSelf(boolean moveSelf) {
        this.moveSelf = moveSelf;
    }

    /**
     * 地图自动缩放的时候 边间距
     */
    public void setPadding(int padding) {
        this.padding = padding;
    }

    /**
     * 添加搜索到的数据
     */
    public void setListData(List<? extends MapBaseBean> list) {
        this.list = list;
        removeItemOverlay();
        setItemOverLay();
    }

    /**
     * 清空marker
     */
    public void removeItemOverlay() {
        aMap.clear();
    }

    /**
     * 添加marker
     */
    public void setItemOverLay() {
        double minLat = 0, minLong = 0, maxLat = 0, maxLong = 0;
//        if(list.size() > 1){
//            minLat = Double.valueOf(list.get(0).getY());
//            maxLat = Double.valueOf(list.get(0).getY());
//            minLong = Double.valueOf(list.get(0).getX());
//            maxLong = Double.valueOf(list.get(0).getX());
//        }
        for (int i = 0; i < list.size(); i++) {
            if (TextUtils.isEmpty(list.get(i).getY()) || TextUtils.isEmpty(list.get(i).getX())) {
                continue;
            } else {
                if (minLat == 0) {
                    minLat = Double.valueOf(list.get(i).getY());
                    maxLat = Double.valueOf(list.get(i).getY());
                    minLong = Double.valueOf(list.get(i).getX());
                    maxLong = Double.valueOf(list.get(i).getX());
                }
            }
            LatLng latlng = new LatLng(Double.valueOf(list.get(i).getY()), Double.valueOf(list.get(i).getX()));
            Bitmap bitmap = mMapBaseDrawable.createMarker(list.get(i));
            if(bitmap == null)
                continue;
            BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(bitmap);

            Marker marker = aMap.addMarker(new MarkerOptions().position(latlng)
                    .title(i + "").icon(icon).draggable(true));
            if (Double.valueOf(list.get(i).getY()) < minLat) {
                minLat = Double.valueOf(list.get(i).getY());
            }
            if (Double.valueOf(list.get(i).getY()) > maxLat) {
                maxLat = Double.valueOf(list.get(i).getY());
            }
            if (Double.valueOf(list.get(i).getX()) < minLong) {
                minLong = Double.valueOf(list.get(i).getX());
            }
            if (Double.valueOf(list.get(i).getX()) > maxLong) {
                maxLong = Double.valueOf(list.get(i).getX());
            }
        }
        showSuccess((minLat + maxLat) / 2, (minLong + maxLong) / 2);
        if (list.size() > 1 && moveSelf) {
            LatLng west = new LatLng(minLat, minLong);
            LatLng east = new LatLng(maxLat, maxLong);
            LatLngBounds bounds = new LatLngBounds(west, east);
            touchFlag = false;
            aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, padding),
                    new AMap.CancelableCallback() {
                        @Override
                        public void onFinish() {
                            center = aMap.getCameraPosition().target;
                        }

                        @Override
                        public void onCancel() {
                        }
                    });
        }
        //添加自己位置marker
        if (true) {
            centerMarker = aMap.addMarker(new MarkerOptions()
                    .position(myLoc)
                    .icon(BitmapDescriptorFactory
                            .fromResource(R.mipmap.ic_map_logo))
                    .draggable(true));
        }
    }

    /**
     * 开始定位
     */
    public void startLocation() {
        locationClient.addLocationListener(this);
    }

    /**
     * 添加marker和pop的bitmap的基类
     *
     * @param mMapBaseDrawable
     */
    public void setMapBaseDrawable(MapBaseDrawable mMapBaseDrawable) {
        this.mMapBaseDrawable = mMapBaseDrawable;
    }

    @Override
    public void onTouch(MotionEvent motionEvent) {
        touchFlag = true;
    }

    /**
     * 可视范围改变时回调此方法
     */
    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
    }

    /**
     * 用户对地图做出一系列改变地图可视区域的操作（如拖动、动画滑动、缩放）完成之后回调此方法
     */
    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        LatLng moveCenter = cameraPosition.target;
        float distance;
        if (center == null) {
            distance = MAX_DISTANCE;
        } else {
            distance = AMapUtils.calculateLineDistance(center, moveCenter);
        }
        if (moveSelf) {
            moveSelf = false;
            return;
        }
        if (!touchFlag)
            return;
        float nowZoom = cameraPosition.zoom;
        if (nowZoom <= ZOOM_DEFAULT) {
            if (zoom > ZOOM_DEFAULT) {//地图缩小  显示区域模块
                mapZoomChange(moveCenter, 0);
                zoom = nowZoom;
                return;
            }
        } else if (nowZoom >= ZOOM_DETAIL) {
            if (zoom < ZOOM_DETAIL) {//地图放大，请求详细楼盘
                center = moveCenter;
                mapZoomChange(moveCenter, 1);
                zoom = nowZoom;
                return;
            }
        }
        if (distance >= MAX_DISTANCE) {
            center = moveCenter;
            mapMoveFinishCallBack(center, distance);
        }
    }

    /**
     * 地图移动结束后调此方法 距离达到要求
     */
    protected abstract void mapMoveFinishCallBack(LatLng center, float distance);

    /**
     * 改变zoom时触发
     */
    public void mapZoomChange(LatLng center, int flag) {

    }

    ;

    /**
     * 自定义弹出window
     */
    protected abstract View setWindowData(Marker marker);

    /**
     * 自定义点击window事件
     */
    protected abstract void mapInWindorClick(Marker marker);

    /**
     * marker被点击
     */
    protected abstract void mapMarkerClick(Marker marker);

    @Override
    public boolean onMarkerClick(Marker marker) {
//        marker.showInfoWindow();
        mapMarkerClick(marker);
        return true;
    }

    @Override
    public void onMapClick(LatLng latLng) {

    }

    /**
     * 获取应该显示的地图大小中心点位置
     */
    public void showSuccess(double latidude, double longitude) {

    }

    /**
     * 获取当前地图缩放等级
     */
    public float getAMapZoom() {
        return aMap.getCameraPosition().zoom;
    }

    /**
     * 当marker 的信息窗口被点击时，回调此方法。
     */
    @Override
    public void onInfoWindowClick(Marker marker) {
        mapInWindorClick(marker);
    }

    /**
     * 提供了一个给默认信息窗口定制内容的方法。
     */
    @Override
    public View getInfoWindow(Marker marker) {
        return setWindowData(marker);
    }

    /**
     * 提供了一个给默认信息窗口定制内容的方法。
     */
    @Override
    public View getInfoContents(Marker marker) {
        return setWindowData(marker);
    }
}
